package controllers

import (
	"WORKSPACE/models"
	"WORKSPACE/pkg/app"
	"WORKSPACE/pkg/e"
	"WORKSPACE/services"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
	"time"
)

func GetOrders(c *gin.Context){
	err, info, total := services.GetAllorders()
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}
	app.OK(c, map[string]interface{}{"value": info, "total": total},"查询成功")
}

func DelOrders(c *gin.Context){
	id := c.Query("orderId")

	fmt.Println(id)
	if id == ""{
		app.INFO(c,30001,"参数错误")
		return
	}
	err := services.Deldetails(id)
	services.Delorders(id)
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}
	app.OK(c, map[string]interface{}{},"删除成功")
}

func UpdateOrders(c *gin.Context){
	data, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(data, &m)
	orderId := com.StrTo(m["orderId"]).MustInt()
	ConsumerId := com.StrTo(m["ConsumerId"]).MustInt()
	goodsId := m["goodsId"]
	orderDate := time.Now()
	transRequest := m["transRequest"]
	isAvailable := m["isAvailable"]
	TransFare := com.StrTo(m["TransFare"]).MustInt()
	if m["orderId"] == ""{
		app.INFO(c, 30000, "参数非法")
		return
	}

	err := services.Updateorders(models.Orders{Order_id: orderId, Consumer_id: ConsumerId, Goods_id: goodsId, Order_date: orderDate, Trans_request: transRequest, Is_available: isAvailable, Trans_fare: TransFare})
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}
	app.OK(c, map[string]interface{}{},"更新成功！")
}

func AddOrders(c *gin.Context){
	data, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(data, &m)
	consumerId := com.StrTo(m["Consumer_id"]).MustInt()
	goodsId := m["Goods_id"]
	orderDate := time.Now()
	transRequest := m["Trans_request"]
	fmt.Println(m)
	//if m["OrderId"] == ""{
	//	app.INFO(c, 30000, "参数非法")
	//	return
	//}

	err := services.Addorders(models.Orders{Consumer_id: consumerId, Goods_id: goodsId,Order_date: orderDate,Trans_request: transRequest})
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}
	app.OK(c, map[string]interface{}{},"添加成功！")
}